package com.sy.musicapp.model

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sy.musicapp.intent.network.MusicAppNetwork
import com.sy.musicapp.showToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

/**
 * 搜索模块ViewModel
 * @author SY
 * @since 2022-02-21 21:32
 **/
class SearchViewModel : ViewModel() {

    var hotKey = MutableStateFlow(HotKey.Empty)
    var searchResultList = MutableStateFlow(listOf<Music>())


    init {
        getHotkey()
    }

    fun getHotkey() {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                MusicAppNetwork.getHotkey().body()?.let {
                    hotKey.value = it
                }
            } catch (e: Exception) {
                "获取热搜失败".showToast()
                e.printStackTrace()
            }
        }
    }


    fun searchKey(key: String) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                MusicAppNetwork.getSearchResult(key).body()?.let {
                    searchResultList.value = it
                }
            } catch (e: Exception) {
                "搜索失败，请重试".showToast()
                e.printStackTrace()
            }
        }

    }

    fun resetAll() {
        /** 不处理 */
    }
}